package cn.xfdzx.android.apps.shop.fragment.home;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.ClassMarketPurchaseActivity;
import cn.xfdzx.android.apps.shop.activity.HomeSearchActivity;
import cn.xfdzx.android.apps.shop.activity.LocationActivity;
import cn.xfdzx.android.apps.shop.activity.MainActivity;
import cn.xfdzx.android.apps.shop.activity.WebViewActivity;
import cn.xfdzx.android.apps.shop.activity.XFDGoodsDeatailsActivity;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.activity.ruzhu.AgreementActivity;
import cn.xfdzx.android.apps.shop.adapter.GoodsLimitList_HomePageAdapter;
import cn.xfdzx.android.apps.shop.adapter.GoodsMiaoShaList_HomePageAdapter;
import cn.xfdzx.android.apps.shop.adapter.HomeMarketFamilyTypeAdapter;
import cn.xfdzx.android.apps.shop.adapter.HomeMarketGoodTitleAdapter;
import cn.xfdzx.android.apps.shop.adapter.HomeVPAdapter;
import cn.xfdzx.android.apps.shop.adapter.MarketClassGVAdapter;
import cn.xfdzx.android.apps.shop.adapter.MarketZiyingGVAdapter;
import cn.xfdzx.android.apps.shop.adapter.TabFragmentAdapter;
import cn.xfdzx.android.apps.shop.adapter.XfdTimeZhiNanAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpFragment;
import cn.xfdzx.android.apps.shop.bean.BaseObjectBean;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.FamilyBuyBeen;
import cn.xfdzx.android.apps.shop.bean.FoundGoodTitleBeen;
import cn.xfdzx.android.apps.shop.bean.GoodsLimitBean;
import cn.xfdzx.android.apps.shop.bean.GoodsMiaoSBean;
import cn.xfdzx.android.apps.shop.bean.HomeMarketInitDataBeen;
import cn.xfdzx.android.apps.shop.bean.HomeMarketSelectBeen;
import cn.xfdzx.android.apps.shop.bean.Qc_MessageBeen;
import cn.xfdzx.android.apps.shop.bean.SelfOwnedShopBeen;
import cn.xfdzx.android.apps.shop.contract.HomeMarketContract;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.evenbus.HomeAdressMessage;
import cn.xfdzx.android.apps.shop.evenbus.HomeFlushCarData;
import cn.xfdzx.android.apps.shop.evenbus.MarketNearShopSelectMessage;
import cn.xfdzx.android.apps.shop.evenbus.PostCarNumMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMarketBottomMessage;
import cn.xfdzx.android.apps.shop.presenter.HomeMarketPresenter;
import cn.xfdzx.android.apps.shop.qcshop.Qc_ShopActivity;
import cn.xfdzx.android.apps.shop.util.CommonUtil;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.ScrollSpeedLinearLayoutManger;
import cn.xfdzx.android.apps.shop.util.SendValidateTimerUtil;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.TimeUtil;
import cn.xfdzx.android.apps.shop.util.ToastUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.view.AutoPollRecyclerView;
import cn.xfdzx.android.apps.shop.view.CheckableTextView;
import cn.xfdzx.android.apps.shop.view.IArcView;
import cn.xfdzx.android.apps.shop.view.MyGridView;
import cn.xfdzx.android.apps.shop.view.RoundRelativeLayout;
import cn.xfdzx.android.apps.shop.zxing.android.CaptureActivity;

import static cn.xfdzx.android.apps.shop.activity.MainActivity.TYPE_IS_RETAIL;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/**
 * @author gzk
 * @date 2020/3/26 0026
 * description：新发地市场采购
 */
public class HomeMarketPurchaseFragment extends BaseMvpFragment<HomeMarketPresenter> implements HomeMarketContract.View,
        OnBannerListener, View.OnClickListener {

    Banner banner;
    @BindView(R.id.tv_near_shop)
    TextView tvNearShop;
    @BindView(R.id.view_near_shop)
    View viewNearShop;
    @BindView(R.id.rl_near_shop)
    RelativeLayout rlNearShop;
    @BindView(R.id.tv_found_good)
    TextView tvFoundGood;
    @BindView(R.id.view_found_good)
    View viewFoundGood;
    @BindView(R.id.rl_found_good)
    RelativeLayout rlFoundGood;
    @BindView(R.id.rv_found_good_title)
    RecyclerView rvFoundGoodTitle;
    @BindView(R.id.tv_home_shop_comprehensive_sequencing)
    CheckableTextView tvHomeShopComprehensiveSequencing;
    @BindView(R.id.tv_home_shop_sales)
    CheckableTextView tvHomeShopSales;
    @BindView(R.id.rl_near_title)
    RelativeLayout rlNearTitle;
    @BindView(R.id.rv_xfd_goods_select)
    RecyclerView rvXfdGoodsSelect;
    @BindView(R.id.ll_bottom)
    RoundRelativeLayout llBottom;
    private ImageView ivLocation;
    MyGridView gvMarketClass;//中间显示5个分类
    GridView mgvZiying;//自营4个分类
    TextView tvXfdMore;//更多
    TextView tvXfdName;//名称
    //    ImageView ivMarketActivity;//活动图
    AutoPollRecyclerView aprvView;//
    //    RecyclerView rvXfdGoodsSelect;//精选货源
    SmartRefreshLayout mRefreshLayout;
    private LinearLayout llActivity;//活动
    private RelativeLayout rlHomeZiying;
    private ArrayList<HomeMarketSelectBeen.DataBean> selectList = new ArrayList<>();
    private int page = 1;
    private int limit = Constants.LIMIT;
    private LinearLayout ll_goruzhu;//去入驻
    private TextView tv_goruzhu;//点击去入驻
    private int isFirstShow;//判断是否是第一次显示已经入驻成功弹窗，1登录成功2已经提示
    private Dialog addSureDialog;
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";

    private MarketClassGVAdapter marketClassGVAdapter;
    private MarketZiyingGVAdapter marketZiyingGVAdapter;
    private XfdTimeZhiNanAdapter zhiNanAdapter;
    //    private FineSelectXfdAdapter fineSelectXfdAdapter;
    private boolean is_free_mail_activity;//活动是否开始
    private TextView tv_monthtimes;//，免费次数

    private TextView tvHomeAddress;//定位地址
    private LinearLayout llHomeSearch;//搜索响应
    private ImageView ivMessage;//消息
    private LinearLayout llState;
    private AppBarLayout appBar;
    private RelativeLayout.LayoutParams item_bar;
    private float LL_SEARCH_MIN_TOP_MARGIN, LL_SEARCH_MAX_TOP_MARGIN, LL_SEARCH_MAX_WIDTH, LL_SEARCH_MIN_WIDTH, TV_TITLE_MAX_TOP_MARGIN;
    private ViewGroup.MarginLayoutParams searchLayoutParams, titleLayoutParams;
    private Context mContext;
    private IArcView iavBg;//椭圆背景

    private RecyclerView recycle_limit, recycle_ms;
    private GoodsLimitList_HomePageAdapter limitListHomePageAdapter;
    private List<GoodsLimitBean.DataBean> limitDataBeans;
    private GoodsMiaoShaList_HomePageAdapter goodsMiaoShaListHomePageAdapter;
    private List<GoodsMiaoSBean.DataBean.GoodsBean> msdataBeans;
    private TextView tv_state, tv_time;
    private long service_time;
    private long start_time;
    private long end_time;

    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List<FoundGoodTitleBeen.DataBean> mTitleList = new ArrayList<>();
    private boolean is_miao = false;
    private boolean is_xian = false;

    private List<Fragment> mFragments;
    private TabFragmentAdapter mTabFragmentAdapter;
    private HomeMarketGoodTitleAdapter homeMarketGoodTitleAdapter;
    String select_id = ""; //默认请求的id
    String selId = "";
    private boolean flag = true;
    private int sel;//在当前排序或者销量的筛选条件 1 综合  2 销量
    private RelativeLayout rel_family_look_all;
    private HomeMarketFamilyTypeAdapter adapter;

    @Override
    protected void initView(View view) {
        mContext = getActivity();
        EventBus.getDefault().register(this);

        mPresenter = new HomeMarketPresenter();
        mPresenter.attachView(this);

        initFindViewId(view);
        initHigh();
        tv_goruzhu.setOnClickListener(this);
        init();
        initActiveRecycle();

        mFragments = new ArrayList<>();

        mPresenter.initData();
        mPresenter.selfOwnedShop("4");
        mPresenter.getGoodsLimitList(true, false, "2", 1);
        mPresenter.getGoodsMiaoShaList(true, false, "2", 1);
//分类标题
        mPresenter.initTitle("-1", "3");

        mPresenter.familyBuy("1");//批发家庭购


        initTabTitle();

        initBuyFamily();//家庭购
    }

    private void initBuyFamily() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, RecyclerView.HORIZONTAL, false);

        rvXfdGoodsSelect.setLayoutManager(linearLayoutManager);

        adapter = new HomeMarketFamilyTypeAdapter(list);
        rvXfdGoodsSelect.setAdapter(adapter);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                List<FamilyBuyBeen.DataBean.FamilyShoppingActivityBean> data = adapter.getData();
                mPresenter.addCar("0", "", data.get(position).getGoods_id() + "", "1", position, data.get(position).getCart_num() + 1);

            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {


                List<FamilyBuyBeen.DataBean.FamilyShoppingActivityBean> data = adapter.getData();
                if (data.get(position).getType() == 0) {
                    Intent intent = new Intent(getActivity(), XFDGoodsDeatailsActivity.class);
                    intent.putExtra("good_id", data.get(position).getGoods_id() + "");
                    getActivity().startActivity(intent);
                } else {

                    Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                    intent1.putExtra("url", Constants.FAMILY_BUY);
                    intent1.putExtra("title", "超值家庭购");
                    startActivity(intent1);
                }

            }
        });


    }

    private String[] titles = new String[]{"附近商家", "发现好货"};

    /**
     * 初始化底部发现好货和门店事件
     */
    private void initTabTitle() {

        mFragments = new ArrayList<>();
        mFragments.add(MarketNearShopFagment.newInstance(""));
        mFragments.add(MarketViewPageFragment.newInstance(""));
        HomeVPAdapter homeVPAdapter = new HomeVPAdapter(getChildFragmentManager(), titles, mFragments);
        mViewPager.setAdapter(homeVPAdapter);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 1) {
                    tvFoundGood.setTextColor(getResources().getColor(R.color.colorPrimary));
                    tvNearShop.setTextColor(getResources().getColor(R.color.color_545454));
                    viewFoundGood.setVisibility(View.VISIBLE);
                    viewNearShop.setVisibility(View.GONE);
                    rvFoundGoodTitle.setVisibility(View.VISIBLE);
                    rlNearTitle.setVisibility(View.GONE);
                    tvFoundGood.setTypeface(Typeface.DEFAULT_BOLD);
                    tvNearShop.setTypeface(Typeface.DEFAULT);
                    if (flag) {
//                        EventBus.getDefault().post(new MarketFoundGoodSelectIdMessage(""));
//                        EventBus.getDefault().post(new UpdateMarketBottomMessage(""));
                        flag = false;
                    }
                } else {
                    tvFoundGood.setTextColor(getResources().getColor(R.color.color_545454));
                    tvNearShop.setTextColor(getResources().getColor(R.color.colorPrimary));
                    viewFoundGood.setVisibility(View.GONE);
                    viewNearShop.setVisibility(View.VISIBLE);
                    rvFoundGoodTitle.setVisibility(View.GONE);
                    rlNearTitle.setVisibility(View.VISIBLE);

                    tvNearShop.setTypeface(Typeface.DEFAULT_BOLD);
                    tvFoundGood.setTypeface(Typeface.DEFAULT);


                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        rvFoundGoodTitle.setLayoutManager(new GridLayoutManager(mContext, 4));

        homeMarketGoodTitleAdapter = new HomeMarketGoodTitleAdapter(mContext, mTitleList);
        rvFoundGoodTitle.setAdapter(homeMarketGoodTitleAdapter);
        rvFoundGoodTitle.setVisibility(View.GONE);
        rlNearTitle.setVisibility(View.VISIBLE);


        homeMarketGoodTitleAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (selId.equals(mTitleList.get(position).getId() + "")) {
                    selId = "";
                } else {
                    selId = mTitleList.get(position).getId() + "";
                }

                homeMarketGoodTitleAdapter.setSelect_id(selId);

                /**
                 *   默认请求第一个选择的id
                 */
                if (TextUtils.isEmpty(selId)) {
                    EventBus.getDefault().post(new UpdateMarketBottomMessage(select_id));
                } else {
                    EventBus.getDefault().post(new UpdateMarketBottomMessage(selId));
                }
//                EventBus.getDefault().post(new MarketFoundGoodSelectIdMessage(select_id));

            }
        });
    }


    private void initFindViewId(View view) {
        mTabLayout = view.findViewById(R.id.tl_title);
        ivLocation = view.findViewById(R.id.iv_location);
        mViewPager = view.findViewById(R.id.vp_main_two);
        tvHomeAddress = view.findViewById(R.id.tv_home_address);
        llHomeSearch = view.findViewById(R.id.ll_home_search);
        ivMessage = view.findViewById(R.id.iv_message);
        llState = view.findViewById(R.id.ll_state);
        llActivity = view.findViewById(R.id.ll_activity);
        rlHomeZiying = view.findViewById(R.id.rl_home_ziying);

        appBar = view.findViewById(R.id.app_bar);
        banner = view.findViewById(R.id.ll_market_banner);
        tvXfdMore = view.findViewById(R.id.tv_xfd_more);
        tvXfdName = view.findViewById(R.id.tv_xfd_name);
        gvMarketClass = view.findViewById(R.id.gv_market_class);
        mgvZiying = view.findViewById(R.id.mgv_ziying);
//        ivMarketActivity = view.findViewById(R.id.iv_market_activity);
        aprvView = view.findViewById(R.id.aprv_view);
//        rvXfdGoodsSelect = view.findViewById(R.id.rv_xfd_goods_select);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        ll_goruzhu = view.findViewById(R.id.ll_goruzhu);
        tv_goruzhu = view.findViewById(R.id.tv_goruzhu);
        tv_monthtimes = view.findViewById(R.id.tv_monthtimes);
        iavBg = view.findViewById(R.id.iav_bg);
        recycle_limit = view.findViewById(R.id.recycle_limit);
        recycle_ms = view.findViewById(R.id.recycle_ms);
        tv_state = view.findViewById(R.id.tv_state);
        tv_time = view.findViewById(R.id.tv_time);
        rel_family_look_all = view.findViewById(R.id.rel_family_look_all);
        iavBg.setStringColor("#02C557");

        ivLocation.setOnClickListener(this);
        tvHomeAddress.setOnClickListener(this);
        llHomeSearch.setOnClickListener(this);
        ivMessage.setOnClickListener(this);
        rel_family_look_all.setOnClickListener(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_market_purchase;
    }

    private void initActiveRecycle() {
        recycle_limit.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        limitListHomePageAdapter = new GoodsLimitList_HomePageAdapter(limitDataBeans);
        recycle_limit.setAdapter(limitListHomePageAdapter);

        recycle_ms.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        goodsMiaoShaListHomePageAdapter = new GoodsMiaoShaList_HomePageAdapter(msdataBeans);
        recycle_ms.setAdapter(goodsMiaoShaListHomePageAdapter);

    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(mContext);
        llState.setLayoutParams(item_bar);

        searchLayoutParams = (ViewGroup.MarginLayoutParams) llHomeSearch.getLayoutParams();
        titleLayoutParams = (ViewGroup.MarginLayoutParams) tvHomeAddress.getLayoutParams();

        LL_SEARCH_MIN_TOP_MARGIN = CommonUtil.dp2px(mContext, 8f);//布局关闭时顶部距离
        LL_SEARCH_MAX_TOP_MARGIN = CommonUtil.dp2px(mContext, 48f);//布局默认展开时顶部距离
        LL_SEARCH_MAX_WIDTH = CommonUtil.getScreenWidth(mContext) - CommonUtil.dp2px(mContext, 30f);//布局默认展开时的宽度
        LL_SEARCH_MIN_WIDTH = CommonUtil.getScreenWidth(mContext) - CommonUtil.dp2px(mContext, 82f);//布局关闭时的宽度
        TV_TITLE_MAX_TOP_MARGIN = CommonUtil.dp2px(mContext, 11f);
        //Todo 把这个监听注释
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                float dy = -i * 0.65f;
                float searchLayoutNewTopMargin = LL_SEARCH_MAX_TOP_MARGIN - dy;
                float searchLayoutNewWidth = LL_SEARCH_MAX_WIDTH - dy * 1.3f;//此处 * 1.3f 可以设置搜索框宽度缩放的速率

                float titleNewTopMargin = (float) (TV_TITLE_MAX_TOP_MARGIN - dy * 0.5);

                //处理布局的边界问题
                searchLayoutNewWidth = searchLayoutNewWidth < LL_SEARCH_MIN_WIDTH ? LL_SEARCH_MIN_WIDTH : searchLayoutNewWidth;

                if (searchLayoutNewTopMargin < LL_SEARCH_MIN_TOP_MARGIN) {
                    searchLayoutNewTopMargin = LL_SEARCH_MIN_TOP_MARGIN;
                }

                if (searchLayoutNewWidth < LL_SEARCH_MIN_WIDTH) {
                    searchLayoutNewWidth = LL_SEARCH_MIN_WIDTH;
                }

                float titleAlpha = 255 * titleNewTopMargin / TV_TITLE_MAX_TOP_MARGIN;
                if (titleAlpha < 0) {
                    titleAlpha = 0;
                }

                //设置相关控件的LayoutParams  此处使用的是MarginLayoutParams，便于设置params的topMargin属性
                tvHomeAddress.setTextColor(tvHomeAddress.getTextColors().withAlpha((int) titleAlpha));
                titleLayoutParams.topMargin = (int) titleNewTopMargin;
                tvHomeAddress.setLayoutParams(titleLayoutParams);

                searchLayoutParams.topMargin = (int) searchLayoutNewTopMargin;
                searchLayoutParams.width = (int) searchLayoutNewWidth;
                llHomeSearch.setLayoutParams(searchLayoutParams);
            }
        });
    }

    private void init() {
        //设置内置样式，共有六种可以点入方法内逐一体验使用。
        banner.setBannerStyle(BannerConfig.NOT_INDICATOR);
        //设置图片加载器，图片加载器在下方
        banner.setImageLoader(new MyLoader());
        //设置轮播的动画效果，内含多种特效，可点入方法内查找后内逐一体验
        banner.setBannerAnimation(Transformer.Default);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
//        //设置指示器的位置，小点点，左中右。
//        banner.setIndicatorGravity(BannerConfig.CENTER)
//                //以上内容都可写成链式布局，这是轮播图的监听。比较重要。方法在下面。
//                .setOnBannerListener(this);
        marketClassGVAdapter = new MarketClassGVAdapter(getActivity());
        gvMarketClass.setAdapter(marketClassGVAdapter);
        gvMarketClass.setSelector(new ColorDrawable(Color.TRANSPARENT));

        marketZiyingGVAdapter = new MarketZiyingGVAdapter(getActivity());
        mgvZiying.setAdapter(marketZiyingGVAdapter);
        mgvZiying.setSelector(new ColorDrawable(Color.TRANSPARENT));
        //广告图
//        ivMarketActivity.setBackgroundResource(R.drawable.image_shichang_center);
        zhiNanAdapter = new XfdTimeZhiNanAdapter(getContext());
        LinearLayoutManager layoutManager = new ScrollSpeedLinearLayoutManger(getActivity());
        layoutManager.setSmoothScrollbarEnabled(true);
        layoutManager.setAutoMeasureEnabled(true);
        aprvView.setLayoutManager(layoutManager);// 布局管理器。
        aprvView.setHasFixedSize(true);// 如果Item够简单，高度是确定的，打开FixSize将提高性能。
        aprvView.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画，加也行，不加也行。
        aprvView.setAdapter(zhiNanAdapter);


        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //ToDO
                mPresenter.initData();
                mPresenter.selfOwnedShop("4");
                mPresenter.getGoodsLimitList(true, false, "2", 1);
                mPresenter.getGoodsMiaoShaList(true, false, "2", 1);
                mPresenter.initTitle("-1", "3");

//                mPresenter.initTitle("-1", "3");

                mRefreshLayout.finishRefresh(300);
                mPresenter.familyBuy("1");

                EventBus.getDefault().post(new MarketNearShopSelectMessage(sel));//刷新附近商店

                if (TextUtils.isEmpty(selId)) {
                    EventBus.getDefault().post(new UpdateMarketBottomMessage(select_id));
                } else {
                    EventBus.getDefault().post(new UpdateMarketBottomMessage(selId));
                }
//                EventBus.getDefault().post(new UpdateMarketBottomMessage(select_id));//刷新发现好货数据


            }
        });

        tv_goruzhu.setOnClickListener(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        //结束轮播
        banner.stopAutoPlay();
        super.onStop();
    }

    @Override
    public void showLoading() {
        if (TYPE_IS_RETAIL == 1) {
            if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
                ProgressDialog.getInstance().show(getActivity());
            }
        }
    }

    @Override
    public void hideLoading() {
        if (TYPE_IS_RETAIL == 1) {
            ProgressDialog.getInstance().dismiss();
        }
    }


    @Override
    public void onError(Throwable throwable) {

        Toast.makeText(getActivity(), getResources().getString(R.string.the_server_is_busy_please_try_again_later), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onInitDataSuccess(BaseObjectBean<HomeMarketInitDataBeen> bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            initBanner(bean.getData());
            initCategory(bean.getData());
//            initZhiNan(bean.getData());
            if (EmptyUtil.isNotEmpty(bean.getData().getActivity().getFree_mail_activity())) {
                if (EmptyUtil.isNotEmpty(bean.getData().getActivity().getFree_mail_activity().isIs_free_mail_activity())) {
                    is_free_mail_activity = bean.getData().getActivity().getFree_mail_activity().isIs_free_mail_activity();

                    tv_monthtimes.setText(bean.getData().getActivity().getFree_mail_activity().getFree_mail_activity_number() + "次");
                }


                if (EmptyUtil.isNotEmpty(APP_TOKEN)) {
                    if (UtilsData.getPreference(getActivity(), "login").getInteger("is_store") == 0) {
                        if (is_free_mail_activity) {
                            ll_goruzhu.setVisibility(View.VISIBLE);
                        } else {
                            ll_goruzhu.setVisibility(View.GONE);
                        }

                    } else {
                        ll_goruzhu.setVisibility(View.GONE);
                    }
                } else {
                    //活动开始
                    if (is_free_mail_activity) {
                        ll_goruzhu.setVisibility(View.VISIBLE);
                    } else {
                        ll_goruzhu.setVisibility(View.GONE);
                    }
                }
            }
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    private void initZhiNan(HomeMarketInitDataBeen data) {

        zhiNanAdapter.setData(data.getXfdPriceArray());
        aprvView.start();

    }

    private void initCategory(final HomeMarketInitDataBeen result) {
        marketClassGVAdapter.setData((ArrayList<HomeMarketInitDataBeen.IndexWholesaleCategoryBean>) result.getIndexWholesaleCategory());
        gvMarketClass.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), ClassMarketPurchaseActivity.class);
                intent.putExtra("title_name", result.getIndexWholesaleCategory().get(i).getName());
                intent.putExtra("id", result.getIndexWholesaleCategory().get(i).getId() + "");
                getActivity().startActivity(intent);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!aprvView.isStart()) {
            aprvView.start();
        }
        if (EmptyUtil.isNotEmpty(APP_TOKEN)) {
            if (isFirstShow == 1) {//去登录了
                isFirstShow = 2;
//                addSureDialog = Utils.addSureDialog(getActivity(),R.layout.dialog_alrealystore);
//                addSureDialog.show();
            }

            if (UtilsData.getPreference(getActivity(), "login").getInteger("is_store") == 0) {
                if (is_free_mail_activity) {
                    ll_goruzhu.setVisibility(View.VISIBLE);
                } else {
                    ll_goruzhu.setVisibility(View.GONE);
                }

            } else {
                ll_goruzhu.setVisibility(View.GONE);
            }
        } else {
            //活动开始
            if (is_free_mail_activity) {
                ll_goruzhu.setVisibility(View.VISIBLE);
            } else {
                ll_goruzhu.setVisibility(View.GONE);
            }
        }


    }

    @Override
    public void onPause() {
        if (aprvView.isStart()) {
            aprvView.stop();
        }

        super.onPause();
    }

    private void initBanner(HomeMarketInitDataBeen bean) {
        List<String> imageUrls = new ArrayList<>();
        for (int i = 0; i < bean.getBannersWholesale().size(); i++) {
            imageUrls.add(bean.getBannersWholesale().get(i).getPic());
        }
        //设置图片网址或地址的集合
        banner.setImages(imageUrls);

        //必须最后调用的方法，启动轮播图。
        banner.start();

    }

    @Override
    public void onInitSelectDataSuccess(HomeMarketSelectBeen bean) {
        //过时不用了
//        if (bean.getStatus() == Constants.SUCCESS_CODE) {
//            if (page == 1) {
//                selectList.clear();
//                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
//                    @Override
//                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                        mPresenter.initSelectData(false, false, page + "", limit + "");
//
//                    }
//                });
//            }
//            if (bean.getData().size() == 0) {
//                mRefreshLayout.finishLoadMoreWithNoMoreData();
//            } else {
//                page++;
//            }
//            selectList.addAll(bean.getData());
////            fineSelectXfdAdapter.notifyDataSetChanged();
//        } else {
//            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
//        }
    }

    @Override
    public void onSelfOwnedShopSuccess(SelfOwnedShopBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().size() != 0) {
                if (bean.getData().get(0).getGoods().size() == 0) {
                    rlHomeZiying.setVisibility(View.GONE);
                } else {
                    rlHomeZiying.setVisibility(View.VISIBLE);
                }
                marketZiyingGVAdapter.setData(bean.getData().get(0).getGoods());
                tvXfdName.setText(bean.getData().get(0).getStore_name());
                rlHomeZiying.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        Intent intent = new Intent(getActivity(), XFDShopDetailsActivity.class);
//                        intent.putExtra("shop_id", bean.getData().get(0).getStore_id() + "");
//                        getActivity().startActivity(intent);

                        MainActivity activity = (MainActivity) getActivity();
                        activity.tabBar.setSelectTab(1);
                    }
                });
                mgvZiying.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        Intent intent = new Intent(getActivity(), XFDGoodsDeatailsActivity.class);
                        intent.putExtra("good_id", bean.getData().get(0).getGoods().get(i).getId() + "");
                        getActivity().startActivity(intent);


                    }
                });
            }
        }
    }

    List<FamilyBuyBeen.DataBean.FamilyShoppingActivityBean> list = new ArrayList<>();

    @Override
    public void onFamilyBuySuccess(FamilyBuyBeen bean) {

        if (bean.getData().getFamily_shopping_activity() == null) {
            return;
        }
        if (bean.getData().getFamily_shopping_activity().size() > 0) {
            llBottom.setVisibility(View.VISIBLE);
        }

        list.clear();
        FamilyBuyBeen.DataBean.FamilyShoppingActivityBean familyShoppingActivityBean = new FamilyBuyBeen.DataBean.FamilyShoppingActivityBean();

        familyShoppingActivityBean.setType(FamilyBuyBeen.DataBean.FamilyShoppingActivityBean.TYPEFOOT);
        list.addAll(bean.getData().getFamily_shopping_activity());
        list.add(familyShoppingActivityBean);

        adapter.setNewData(list);


    }


    @Override
    public void getGoodsLimitListSuccess(GoodsLimitBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData())) {
                limitDataBeans = bean.getData();
                if (limitDataBeans.size() != 0) {
                    is_xian = true;
                    if (is_miao) {
                        llActivity.setVisibility(View.VISIBLE);
                    }
                }
                limitListHomePageAdapter.refreshDatas(limitDataBeans);
            }
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getGoodsMiaoShaListSuccess(GoodsMiaoSBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (EmptyUtil.isNotEmpty(bean.getData())) {
                msdataBeans = bean.getData().getGoods();
                if (msdataBeans.size() != 0) {
                    is_miao = true;
                    if (is_xian) {
                        llActivity.setVisibility(View.VISIBLE);
                    }
                }
                goodsMiaoShaListHomePageAdapter.refreshDatas(msdataBeans);
                service_time = bean.getData().getService_time();
                start_time = bean.getData().getStart_time();
                end_time = bean.getData().getEnd_time();
                tv_time.setText(TimeUtil.millis2String(start_time * 1000L, "HH:mm:ss"));
                if (service_time >= start_time && service_time < end_time) {
                    mDisableTimeTemp = end_time - service_time;
                    tv_state.setText("距结束");
                    stopTickWork();
                    startTickWork();
                } else {
                    mDisableTimeTemp = start_time - service_time;
                    tv_state.setText("即将开始");
                    stopTickWork();
                    if (mDisableTimeTemp > 0) {
                        startTickWork();
                    }
                }


            }
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    //分类标题
    @Override
    public void onInitTitleSuccess(FoundGoodTitleBeen bean) {

        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mTitleList.clear();
            mTitleList.addAll(bean.getData());
            Collections.reverse(mTitleList);
            homeMarketGoodTitleAdapter.notifyDataSetChanged();

            try {
                select_id = mTitleList.get(0).getId();
                EventBus.getDefault().post(new UpdateMarketBottomMessage(mTitleList.get(0).getId()));

            } catch (Exception e) {

            }

        }

    }

    private String addressMessage;//当前地址

    //更新地址
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(HomeAdressMessage messageEvent) {
        Log.e("messageEvent", messageEvent.getLng() + "--经纬onefragment度--" + messageEvent.getLat());
        addressMessage = messageEvent.getMessage();
        tvHomeAddress.setText(messageEvent.getMessage());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_goruzhu://去入驻
                if (EmptyUtil.isNotEmpty(APP_TOKEN)) {
                    if (UtilsData.getPreference(getActivity(), "login").getInteger("is_store") == 0) {
                        Intent intent = new Intent(getActivity(), AgreementActivity.class);
                        intent.putExtra("type", "0");
                        startActivity(intent);
                    }
                } else {

                    isFirstShow = 1;
                    Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.iv_location:
            case R.id.tv_home_address:
                if (Utils.isFastClick()) {
                    Intent intent = new Intent(getActivity(), LocationActivity.class);
                    intent.putExtra("pageForm", "first");
                    intent.putExtra("send_to_address", addressMessage);
                    startActivity(intent);
                }
                break;
            case R.id.ll_home_search:
                if (Utils.isFastClick()) {
                    Intent home_search = new Intent(getActivity(), HomeSearchActivity.class);
                    startActivity(home_search);
                }
                break;
            case R.id.iv_message:
                //跳转消息
                /*Intent intent = new Intent(getActivity(), MessageActivity.class);
                startActivity(intent);*/
                //动态权限申请
                if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
                } else {
                    //扫码
                    goScan();
                }
                break;

            case R.id.rel_family_look_all:
                //家庭购 跳转更多


                Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                intent1.putExtra("url", Constants.FAMILY_BUY);
                intent1.putExtra("title", "超值家庭购");
                startActivity(intent1);

                break;
        }
    }

    @OnClick({R.id.rl_near_shop, R.id.rl_found_good, R.id.tv_home_shop_comprehensive_sequencing, R.id.tv_home_shop_sales})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_near_shop://附近好店
                mViewPager.setCurrentItem(0);
                rvFoundGoodTitle.setVisibility(View.GONE);
                rlNearTitle.setVisibility(View.VISIBLE);
                break;
            case R.id.rl_found_good://发现好货
                mViewPager.setCurrentItem(1);
                rvFoundGoodTitle.setVisibility(View.VISIBLE);
                rlNearTitle.setVisibility(View.GONE);
                break;

            case R.id.tv_home_shop_comprehensive_sequencing://综合排序
                tvHomeShopComprehensiveSequencing.setChecked(true);
                tvHomeShopSales.setChecked(false);

                EventBus.getDefault().post(new MarketNearShopSelectMessage(1));
                tvHomeShopComprehensiveSequencing.setTypeface(Typeface.DEFAULT_BOLD);
                tvHomeShopSales.setTypeface(Typeface.DEFAULT);
                sel = 1;
                break;

            case R.id.tv_home_shop_sales://销量
                tvHomeShopComprehensiveSequencing.setChecked(false);
                tvHomeShopSales.setChecked(true);
                EventBus.getDefault().post(new MarketNearShopSelectMessage(2));
                tvHomeShopSales.setTypeface(Typeface.DEFAULT_BOLD);
                tvHomeShopComprehensiveSequencing.setTypeface(Typeface.DEFAULT);
                sel = 2;
                break;


        }
    }

    private void goScan() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SCAN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == -1) {
            if (data != null) {
                //返回的文本内容
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                Qc_MessageBeen ub = new Qc_MessageBeen();
                Gson gson = new Gson();
                ub = gson.fromJson(content, Qc_MessageBeen.class);
                Log.e("shuju", "你扫描到的内容是：" + ub.getBehavior_type());
                if (ub.getBehavior_type().equals("entryStore")) {
                    Intent intent = new Intent(mContext, Qc_ShopActivity.class);
                    intent.putExtra("storeid",ub.getData().getStore_id());
                    intent.putExtra("scantype",ub.getData().getScan_type());
                    startActivity(intent);
                } else {
                    ToastUtil.showShortToast("解析错误！");
                }

            }
        }
    }

    //自定义的图片加载器
    private class MyLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            RoundedCorners roundedCorners = new RoundedCorners(40);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
//         RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(300, 300);
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners);
            options.placeholder(R.drawable.icon_defult)//图片加载出来前，显示的图片
                    .fallback(R.drawable.icon_defult) //url为空的时候,显示的图片
                    .error(R.drawable.icon_defult);

            imageView.setPadding(50, 0, 50, 0);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Intent intent = new Intent(getActivity(), ProcurementHomeActivity.class);
//                    startActivity(intent);

                    Intent intent1 = new Intent(getActivity(), WebViewActivity.class);
                    intent1.putExtra("url", Constants.FAMILY_BUY);
                    intent1.putExtra("title", "超值家庭购");
                    startActivity(intent1);

                }
            });
            Glide.with(context).load(path).apply(options.transform(new CenterCrop(), roundedCorners)).into(imageView);
        }

    }

    public static HomeMarketPurchaseFragment newInstance() {
        Bundle bundle = new Bundle();
//        bundle.putString("item", "UserPostFragment");
//        bundle.putLong(Constants.UID, userUid);
        HomeMarketPurchaseFragment fragment = new HomeMarketPurchaseFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean, int position, int total_num) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            Toast.makeText(getActivity(), "加入购物车成功", Toast.LENGTH_SHORT).show();
//            mFamilyList.get(position).setCart_num(total_num);
//            adapter.notifyItemChanged(position);
//            mPresenter.familyBuy("1");
            EventBus.getDefault().post(new PostCarNumMessage());
            EventBus.getDefault().post(new HomeFlushCarData());

        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void OnBannerClick(int position) {

    }

    @Override
    public void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (null != addSureDialog) {
            addSureDialog.dismiss();
            addSureDialog = null;
        }
        if (mTimer != null) {
            mTimer.stopWork();
        }
        super.onDestroy();
    }

    //活动开始前倒计时
    private SendValidateTimerUtil mTimer = new SendValidateTimerUtil();
    private long mDisableTimeTemp = 0;
    private int countDown;//活动倒计时秒数

    /**
     * 开启倒计时
     */
    public void startTickWork() {

        mTimer.startWork(0, 1000, new SendValidateTimerUtil.SDTimerListener() {
            @Override
            public void onWorkMain() {
                if (service_time >= start_time && service_time < end_time) {
                    tickWork();
                } else {
                    tickWorkFront();
                }

            }

            @Override
            public void onWork() {
            }
        });
        // }
    }

    /**
     * 每秒钟调用一次
     */
    private void tickWork() {
        mDisableTimeTemp--;
        if (mDisableTimeTemp >= 0) {
            //执行
            tv_time.setText(TimeUtil.formattedTime(mDisableTimeTemp));
        } else {
            page = 1;
            mPresenter.getGoodsMiaoShaList(true, true, "2", page);
//            //执行
//            tv_time.setText(TimeUtil.millis2String(start_time*1000L,"HH:mm:ss"));
//            tv_state.setText("即将开始");

        }
    }

    /**
     * 活动开始前
     * 每秒钟调用一次
     */
    private void tickWorkFront() {
        mDisableTimeTemp--;

        if (mDisableTimeTemp >= 0) {
            //执行
        } else {//活动开始请求接口
            page = 1;
            mPresenter.getGoodsMiaoShaList(true, true, "2", page);
        }
    }

    public void stopTickWork() {
        mTimer.stopWork();
        //mDisableTimeTemp = countDown;

    }


    //购物车数据改变刷新首页数据  购物车角标数量展示
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void flushHomeCarData(HomeFlushCarData messageEvent) {
        if (TextUtils.isEmpty(selId)) {
            EventBus.getDefault().post(new UpdateMarketBottomMessage(select_id));
        } else {
            EventBus.getDefault().post(new UpdateMarketBottomMessage(selId));
        }

        mPresenter.familyBuy("1");//批发家庭购

    }


}
